package com.yxuan.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.yxuan.springboot.CustomizedException.DefaultException;
import com.yxuan.springboot.WxPayUtil.HttpUtils;
import com.yxuan.springboot.WxPayUtil.WxPayCallbackUtil;
import com.yxuan.springboot.constant.config.WxPayConfig;
import com.yxuan.springboot.constant.config.WxPayConfigForAC;
import com.yxuan.springboot.model.*;
import com.yxuan.springboot.service.*;
import com.yxuan.springboot.util.MD5Util;
import com.yxuan.springboot.util.Result;
import com.yxuan.springboot.util.VerificationCodeUtil;
import com.yxuan.springboot.util.WxPayUtilForAC;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author zchao
 *   AcuserLogin控制器
 * @date 2024-05-16 18:10:48
 */
@Slf4j
@Controller
@Api(tags = "公众号用户登录表")
@RequestMapping(value = "/acuserlogin", method = {RequestMethod.POST,RequestMethod.GET})
public class AcuserLoginController extends BaseController<AcuserLogin>{

    @Autowired
    private AcuserLoginService acuserLoginService;

    @Resource(name = "verifierAC")
    private Verifier verifierAC;

    @Resource
    private WxPayConfigForAC wxPayConfigForAC;

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private KamilsService kamilsService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserVipService userVipService;

    /**
     * 公众号登录
     */
    @ApiOperation(value = "微信登录",notes = "微信登录")
    @ResponseBody
    @RequestMapping("/wxlogin")
    public Result wxlogin(String code) throws Exception {
        return acuserLoginService.wxlogin(code);
    }

    /*
     * 公众号支付
     * */
    @ApiOperation("JSApi支付根据订单返回prepay_id参数")
    @ResponseBody
    @RequestMapping("/JSApiPayForPrepayid2")
    public Result ACJSApiPay(@RequestParam String orderId, @RequestParam String openid)throws Exception{
        return acuserLoginService.ACJsApiPay(orderId,openid);
    }

    private WxPayConfig getWxPayConfig(){
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppid(wxPayConfigForAC.getAppid());
        wxPayConfig.setMchSerialNo(wxPayConfigForAC.getMchSerialNo());
        wxPayConfig.setPrivateKeyPath(wxPayConfigForAC.getPrivateKeyPath());
        wxPayConfig.setMchId(wxPayConfigForAC.getMchId());
        wxPayConfig.setKey(wxPayConfigForAC.getKey());
        wxPayConfig.setDomain(wxPayConfigForAC.getDomain());
        wxPayConfig.setNotifyDomain(wxPayConfigForAC.getNotifyDomain());
        return wxPayConfig;
    }

    @ApiOperation("微信支付回调接口")
    @PostMapping("/wx/callback")
    public String courseNative(HttpServletRequest request, HttpServletResponse response) throws DefaultException {
        return WxPayCallbackUtil.wxPaySuccessCallback(request, response, verifierAC, getWxPayConfig(), callbackData -> {
            // TODO 处理你的业务逻辑，下面说一下一般业务逻辑处理方法
            log.info("微信支付回调返回的信息：{}", callbackData);
            // 1.根据订单id获取订单信息
            String orderId = callbackData.getOrderId();
            String tradestate = callbackData.getTradestate();
            // 2.判断金额是否相符，如果不相符则调用退款接口，并取消该订单，通知客户支付金额不符

            // 3.查询订单状态是否是未支付，如果是未支付则改为已支付，填充其他逻辑，
            if ("SUCCESS".equals(tradestate)) {
                //支付成功，你的业务逻辑
                log.info("支付成功");
//                //将订单状态改成已支付
//                Orders order = new Orders();
//                order.setOrderId(orderId);
//                order.setOrdersState("1");
//                try {
//                    //修改订单支付状态
//                    ordersService.upd(order);
//
//                    //根据orderid找到userid锁定用户
//                    Orders targetOrder = ordersService.findObjectByPramas(order);
//                    String userId = targetOrder.getUserLoginId();
//
//                    //修改用户vip表里的数据
//                    UserVip userVip = new UserVip();
//                    userVip.setUserId(Integer.valueOf(userId));
//
//                    log.info("goodsName为:"+targetOrder.getName());
//                    Result result = userVipService.updateVipByPay(Integer.valueOf(userId), targetOrder.getName());


                //查询订单状态是否已支付，若已支付则跳过
                Orders orders = new Orders();
                orders.setOrderId(orderId);
                orders.setOrdersState("1");
                Orders objectByPramas = null;
                try {
                    objectByPramas = ordersService.findObjectByPramas(orders);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (objectByPramas == null){

                    try {


                        //        修改订单状态
                        ordersService.upd(orders);

                        Orders targetOrder = ordersService.findObjectByPramas(orders);
                        Orders orders1 = ordersService.findObjectByPramas(orders);
//      搜索该商品的名称
                        Goods goods = new Goods();
                        goods.setId(Integer.valueOf(orders1.getGoodsId()));
                        Goods goods1 = goodsService.findObjectByPramas(goods);

                        UserVip userVip = new UserVip();
                        userVip.setUserId(Integer.valueOf(targetOrder.getUserLoginId()));
                        UserVip userVip1 = userVipService.findObjectByPramas(userVip);
                        String vipRankMyself = userVip1.getVipRank();
                        Integer getGptTimes = 0;
                        if (userVip1.getGptTimes() == null || userVip1.getGptTimes().equals("")) {
                            getGptTimes = 0;
                        } else {
                            getGptTimes = Integer.valueOf(userVip1.getGptTimes());
                        }

                        Integer getInfoUpdTimes = 0;
                        if (userVip1.getInfoUpdTimes() == null || userVip1.getInfoUpdTimes().equals("")) {
                            getInfoUpdTimes = 0;
                        } else {
                            getInfoUpdTimes = Integer.valueOf(userVip1.getInfoUpdTimes());
                        }

                        Integer getProbabilityTimes = 0;
                        if (userVip1.getProbabilityTimes() == null || userVip1.getProbabilityTimes().equals("")) {
                            getProbabilityTimes = 0;
                        } else {
                            getProbabilityTimes = Integer.valueOf(userVip1.getProbabilityTimes());
                        }
                        switch (goods1.getName()) {
                            case "日会员":
                                userVip.setVipRank("1");
                                userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
                                userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 2));
                                userVip.setGptTimes(String.valueOf(getGptTimes + 5));
                                break;
                            case "周会员":
                                userVip.setVipRank("2");
                                userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
                                userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 3));
                                userVip.setGptTimes(String.valueOf(getGptTimes + 50));
                                break;
                            case "月会员":
                                userVip.setVipRank("3");
                                userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
                                userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 5));
                                userVip.setGptTimes(String.valueOf(getGptTimes + 120));
                                break;
                            default:
                                userVip.setVipRank("1");
                                userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
                                userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 2));
                                userVip.setGptTimes(String.valueOf(getGptTimes + 5));
                                break;
                        }

                        if(Integer.parseInt(userVip.getVipRank()) < Integer.parseInt(vipRankMyself)) {
                            userVip.setVipRank(vipRankMyself);
                        }

                        Date nows = new Date(System.currentTimeMillis());

                        if (userVip1.getExpirationTime() == null || userVip1.getExpirationTime().compareTo(nows) < 0) {
                            LocalDateTime now = LocalDateTime.now();
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                            String formattedNow = now.format(formatter);
                            System.out.println("当前时间：" + formattedNow);
                            LocalDateTime after10Minutes = null;
                            if (goods1.getName().equals("日会员")) {
                                after10Minutes = now.plusMinutes(60 * 24);

                            } else if (goods1.getName().equals("周会员")) {
                                after10Minutes = now.plusMinutes(60 * 24 * 7);

                            } else if (goods1.getName().equals("月会员")) {
                                after10Minutes = now.plusMinutes(60 * 24 * 30);

                            } else {
                                after10Minutes = now.plusMinutes(60 * 24);

                            }
                            String formattedAfter10Minutes = after10Minutes.format(formatter);
                            Date expirationTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(formattedAfter10Minutes);
                            userVip.setExpirationTime(expirationTime);
                        } else {
                            Date date = userVip1.getExpirationTime();

                            // 使用Calendar类将date转换为Calendar对象
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(date);

                            // 在Calendar对象上增加24小时


                            if (goods1.getName().equals("日会员")) {
                                calendar.add(Calendar.HOUR_OF_DAY, 24);
                            } else if (goods1.getName().equals("周会员")) {
                                calendar.add(Calendar.HOUR_OF_DAY, 24 * 7);
                            } else if (goods1.getName().equals("月会员")) {
                                calendar.add(Calendar.HOUR_OF_DAY, 24 * 31);
                            } else {
                                calendar.add(Calendar.HOUR_OF_DAY, 24);
                            }
                            // 将Calendar对象转换为Date对象
                            Date newDate = calendar.getTime();

                            // 使用DateTimeFormatter类将Date对象格式化为指定格式的字符串
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                            String formattedNewDate = LocalDateTime.ofInstant(newDate.toInstant(), ZoneId.systemDefault()).format(formatter);
                            // 使用SimpleDateFormat类将字符串转换为Date对象
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date expirationTime = null;
                            try {
                                expirationTime = sdf.parse(formattedNewDate);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            System.out.println(expirationTime + "===================");

                            // 调用setExpirationTime方法
                            userVip.setExpirationTime(expirationTime);
                            System.out.println(formattedNewDate);

                        }
                        userVipService.upd(userVip);
                        UserVip userVip2 = new UserVip();
                        userVip2.setUserId(Integer.valueOf(targetOrder.getUserLoginId()));
                        userVipService.findObjectByPramas(userVip2);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }


            }


        });
    }

}
